package main

import (
	"context"
	"gitee.com/vwenkk/boomer-grpc"
	"github.com/apex/log"
	sdk "github.com/crawlab-team/crawlab-sdk"
	"github.com/crawlab-team/crawlab-sdk/entity"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"math/rand"
	"sync"
	"time"
)

func main() {
	CrawlabTaskId := "6441029b8f8d9add328b5ce4"
	taskId, _ := primitive.ObjectIDFromHex(CrawlabTaskId)
	var errorItems []entity.Result
	row := entity.Result{
		"Type":        "test",
		"Name":        "name",
		"Error":       "this is a test",
		"Occurrences": 1,
	}
	row.SetTaskId(taskId)
	errorItems = append(errorItems, row)
	sdk.SaveErrorItems(errorItems)

	var (
		expectWorkers                = 1
		expectWorkersMaxWait         = 60 * 3 // 秒速
		spawnCount           int64   = 100    // 总数
		spawnRate            float64 = 1      // 速率
		runTime              int64   = 30000  // 速率
	)

	//log.Logger = log.With().Caller().Logger().Level(zerolog.DebugLevel)

	profile := &boomer.Profile{
		SpawnCount:               spawnCount,
		SpawnRate:                spawnRate,
		RunTime:                  runTime,
		MaxRPS:                   0,
		LoopCount:                0,
		RequestIncreaseRate:      "",
		MemoryProfile:            "",
		MemoryProfileDuration:    0,
		CPUProfile:               "",
		CPUProfileDuration:       0,
		PrometheusPushgatewayURL: "http://10.18.97.253:9091/",
		DisableConsoleOutput:     false,
		DisableCompression:       false,
		DisableKeepalive:         true,
	}
	masterHost := "127.0.0.1"
	masterBoomer := boomer.NewMasterBoomer(masterHost)
	masterBoomer.EnableGracefulQuit(context.Background())
	masterBoomer.SetProfile(profile)
	//masterBoomer.AddOutput(boomer.NewResultOutput())
	masterBoomer.AddOutput(boomer.NewPrometheusPusherOutput("http://10.10.120.121:9091", "boomer", "standalone", time.Now().String()))
	masterBoomer.SetAutoStart()
	masterBoomer.SetDisableKeepAlive(true)
	masterBoomer.SetExpectWorkers(expectWorkers, expectWorkersMaxWait)
	masterBoomer.SetSpawnCount(spawnCount)
	masterBoomer.SetSpawnRate(spawnRate)
	masterBoomer.SetRunTime(runTime)

	go masterBoomer.RunMaster()
	boomer.Events.Subscribe("boomer:hatch", func(workers int64, hatchRate float64) {
		log.Errorf("The master asks me to spawn", workers, "goroutines with a hatch rate of", hatchRate, "per second.")
	})
	initTask := &boomer.Task{
		Weight: 1,
		Name:   "taskInit",
		Fn: func(ctx boomer.Context) {
			//fmt.Println("task init")
			boomer.RecordFailure("tcp", "task-2", rand.Int63n(30)+50, "test exception")

		},
	}
	var tasks []*boomer.Task

	task1 := &boomer.Task{
		Name: "task1",
		Fn: func(ctx boomer.Context) {
			//fmt.Println("task 1")
			boomer.RecordSuccess("tcp", "task-1", rand.Int63n(50)+100, rand.Int63n(100))
			time.Sleep(1 * time.Second)
			//boomer.RecordFailure("tcp", "task-2", rand.Int63n(30)+50, "test exception")

		},
	}

	task2 := &boomer.Task{
		Name: "task1",
		Fn: func(ctx boomer.Context) {
			//fmt.Println("task 2")
			boomer.RecordFailure("tcp", "task-2", rand.Int63n(30)+50, "test exception")
			//boomer.Quit()
			//runtime.Goexit()
			time.Sleep(1 * time.Second)

		},
	}

	tasks = append(tasks, task1, task2)

	wg := sync.WaitGroup{}
	wg.Add(expectWorkers)
	for i := 0; i < expectWorkers; i++ {
		go func() {
			boomer.SetInitTask(initTask)
			boomer.Run(tasks...)
			wg.Done()
		}()
	}

	wg.Wait()

}
